package com.faxsun.web.controller.admin;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baidu.ueditor.define.ActionMap;
import com.baidu.ueditor.define.State;
import com.baidu.ueditor.upload.BinaryUploader;
import com.faxsun.core.persist.entity.BannerPO;
import com.faxsun.core.service.BannerService;
import com.faxsun.upload.UpyunUploader;
import com.faxsun.web.controller.admin.url.AdminViewConstants;

import mblog.web.controller.BaseController;
import mtons.modules.pojos.Data;
import mtons.modules.pojos.Page;

/**
 * Banner管理
 * 
 * @author songdragon
 *
 */
@Controller
@RequestMapping(value = "/admin/banners")
public class BannerManagerController extends BaseController {

	private static final Logger log = LoggerFactory.getLogger(BannerManagerController.class);

	@Autowired
	BannerService bannerService;

	Map<String, Object> conf = null;

	/**
	 * 初始化上传图片所需要的参数
	 */
	public BannerManagerController() {
		conf = new HashMap<String, Object>();
		conf.put("actionCode", ActionMap.UPLOAD_IMAGE);
		conf.put("isBase64", "false");
		conf.put("maxSize", new Long(2048000));
		conf.put("allowFiles", new String[] { ".png", ".jpg", ".jpeg", ".gif", ".bmp" });
		conf.put("fieldName", "upfile");
		conf.put("actionCode", ActionMap.UPLOAD_IMAGE);
	}

	/**
	 * banner列表界面
	 * @param model
	 * @return
	 */
	@RequestMapping("/list")
	public String list(ModelMap model) {
		String url = "/admin/banners/data-url";
		model.addAttribute("url", url);
		model.addAttribute(AdminViewConstants.VIEW, AdminViewConstants.VIEW_BANNER_LIST);

		return AdminViewConstants.VIEW_ADMIN_LAYOUT;
	}

	/**
	 * 添加banner界面
	 * @param banner
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String view(@ModelAttribute("banner") BannerPO banner, @RequestParam(value = "id", required = false) Long id,
			ModelMap model) {

		if(id!=null && id>0){
			banner=this.bannerService.findById(id);
		}
		
		model.addAttribute(AdminViewConstants.VIEW, AdminViewConstants.VIEW_BANNER_ADD);
		model.addAttribute("banner", banner);
		return AdminViewConstants.VIEW_ADMIN_LAYOUT;
	}

	/**
	 * 上传图片到upyun
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	@ResponseBody
	public State uploadImage(HttpServletRequest request) {
		String rootPath = request.getServletContext().getRealPath("/") + "/..";
		conf.put("rootPath", rootPath);
		String savePath = "/banners/info/banner-" + System.currentTimeMillis();
		conf.put("savePath", savePath);
		State state = BinaryUploader.save(request, conf);
		
		UpyunUploader.upload(state, conf);
		return state;
	}

	/**
	 * 保存或更新banner
	 * 
	 * @param banner
	 * @param bindingResult
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public Data add(@ModelAttribute("banner") BannerPO banner, BindingResult bindingResult,
			HttpServletRequest request) {
		Data ret = Data.failure("保存失败");
		if (banner != null && !StringUtils.isEmpty(banner.getUrl())) {
			if (banner.getId() == 0L) {
				bannerService.addBanner(banner);
			} else {
				bannerService.updateBannr(banner);
			}

			if (banner.getId() != 0L) {
				ret = Data.success("保存成功");
			}
		}
		return ret;
	}

	/**
	 * 设置banner是否显示在首页
	 * @param ids
	 * @param isDisplayed
	 * @return
	 */
	@RequestMapping(value = "setselected", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE
			+ ";charset=UTF-8")
	@ResponseBody
	public Data add(@RequestParam(value = "ids", required = true) String ids,
			@RequestParam(value = "selected", required = true) boolean isDisplayed) {
		Data ret = Data.failure("设置Banner失败,Banner" + ids + "不存在");

		String[] idArray = ids.split(",");
		boolean isAllSuccess = true;
		StringBuffer sb = new StringBuffer();
		for (String idString : idArray) {

			try {
				long id = Long.parseLong(idString);
				BannerPO bannerPO = this.bannerService.findById(id);
				if (bannerPO != null) {
					bannerPO.setDisplayed(isDisplayed);
					this.bannerService.updateBannr(bannerPO);
				}
			} catch (Exception e) {
				log.error("", e);
				isAllSuccess = isAllSuccess && false;
				sb.append(idString);
				sb.append(",");
			}

		}
		if (isAllSuccess)
			ret = Data.success("设置Banner成功");
		else {
			sb.deleteCharAt(sb.length() - 1);
			ret.setMessage("设置Banner失败,频道" + sb.toString() + "设置失败");
		}
		return ret;
	}

	/**
	 * JSON获取Post列表数据
	 * 
	 * @param type
	 * @param pageNo
	 * @param max
	 * @param search
	 * @param field
	 * @param model
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/data-url", method = RequestMethod.GET)
	public @ResponseBody BannerTableJSON data(
			@RequestParam(value = "offset", required = false, defaultValue = "1") Integer pageNo,
			@RequestParam(value = "limit", required = false, defaultValue = "10") Integer max,
			@RequestParam(value = "search", required = false, defaultValue = "") String search,
			@RequestParam(value = "sort", required = false) String field, ModelMap model) {
		pageNo = pageNo / max + 1;
		Page page = wrapPage(pageNo);
		page.setMaxResults(max);

		// TODO:按字段排序
		if (StringUtils.isEmpty(search)) {
			page = bannerService.listByPage(page);
		} else {
			// TODO:搜索结果
		}
		BannerTableJSON ret = new BannerTableJSON();
		ret.total = page.getTotalCount();
		ret.rows = (List<BannerPO>) page.getResults();
		return ret;
	}
}

class BannerTableJSON {
	public int total;
	public List<BannerPO> rows;

}